package com.tastyshop.controller;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.tastyshop.domain.Member;
import com.tastyshop.service.Base64;
import com.tastyshop.service.MemberService;

@Controller
public class MyPageController {
	
	@Autowired
	private MemberService service;
	
	// 마이페이지 화면
	@RequestMapping(value = "myPage.do", method = RequestMethod.GET)
	public String myInfoForm(@ModelAttribute Member member, HttpSession session, Model model){
		if(session.getAttribute("email") == null){
			return "main";
		}
		
		String email = (String) session.getAttribute("email");
	
		Member getUserInfo = service.getUserInfo(email);
		
		// 년도 가져오기
		String year = getUserInfo.getBirth().substring(0, 4);
		model.addAttribute("year", year);
		// 월 가져오기
		String getMonth = getUserInfo.getBirth().substring(4, 6);
		if(getMonth.length() == 2){
			String month = getMonth.substring(1);
			model.addAttribute("month", month);
		}else{
			model.addAttribute("month", getMonth);
		}
		// 일 가져오기
		String day = getUserInfo.getBirth().substring(6, 8);
		model.addAttribute("day", day);
		// 성별가져오기
		if(getUserInfo.getGender() == 1){
			String checked = "checked";
			model.addAttribute("man", checked);
		}else{
			String checked = "checked";
			model.addAttribute("wooman", checked);
		}
		// 가입일자 date 타입 string으로 
		DateFormat formatDate = new SimpleDateFormat("yyyy-MM-dd");
		String reg_date = formatDate.format(getUserInfo.getReg_date());
		model.addAttribute("reg_date", reg_date);
		model.addAttribute("member", getUserInfo);
		return "myPage";
	}
	
	// 회원정보수정
	@RequestMapping(value = "modifyUser.do", method = RequestMethod.POST)
	public String modifyUser(@ModelAttribute Member member, Model model, HttpSession session, HttpServletRequest request,
			RedirectAttributes redirectAttributes){
		
		member.setEmail((String) session.getAttribute("email"));		
		String user_name = (String) request.getParameter("user_name");
		String user_pw = (String) request.getParameter("user_pw");
		String encodePassword = new String(Base64.encode(user_pw.getBytes()));
		String mobile = (String) request.getParameter("mobile");
		String year = (String) request.getParameter("year");
		String month = (String) request.getParameter("month");
		if (month.length() == 1) {
			month = "0" + month;
		}
		String day = (String) request.getParameter("day");
		if (day.length() == 1) {
			day = "0" + day;
		}
		String birth = year + month + day;
		String gender = (String) request.getParameter("gender");
		int genderNum = Integer.parseInt(gender);
		        
        member.setUser_name(user_name);
        member.setUser_pw(encodePassword);
        member.setMobile(mobile);
        member.setBirth(birth);
        member.setGender(genderNum);
      	service.modifyUser(member);
      	redirectAttributes.addFlashAttribute("user_name", user_name);
      	return "redirect:modify_result.do";
	}
	
	@RequestMapping(value = "modify_result.do", method = RequestMethod.GET)
	public String modifyResult(){
		return "modify_result";
	}
	
	// 회원탈퇴확인 정보 입력 화면
	@RequestMapping(value = "deleteUser.do", method = RequestMethod.GET)
	public String deleteUser_form(){
		return "deleteUser_form";
	}
	
	// 회원탈퇴실행
	int errorCount = 0;
	@RequestMapping(value = "deleteUser.do", method = RequestMethod.POST)
	public String deleteUser(@ModelAttribute Member member, Model model, HttpSession session){
		String user_pw = member.getUser_pw();
		String encodePassword = new String(Base64.encode(user_pw.getBytes()));
		Map<String, String> map_search = new HashMap<String, String>();
		map_search.put("email", member.getEmail());
		map_search.put("user_pw", encodePassword);
		
		if(service.getIdPwSearch(map_search) == 1){
			service.deleteUser(map_search);
			model.addAttribute("user_name", session.getAttribute("user_name"));
			session.invalidate();
			return "delete_result";
		}else{
			errorCount++;
			switch(errorCount){
			case 1 : String message1 = "첫 번째 입력 오류입니다.";
			         model.addAttribute("message", message1);
			         break;
			case 2 : String message2 = "두 번째 입력 오류입니다.";
			         model.addAttribute("message", message2);
			         break;
			case 3 : String message3 = "세 번째 입력 오류입니다.";
			         model.addAttribute("message", message3);
			         break;
			case 4 : String message4 = "네 번째 입력 오류입니다." + "<br />" + "한 번 더 입력 오류시 자동로그아웃됩니다.";
			         model.addAttribute("message", message4);
			         break;
			case 5 : session.invalidate();
			         return "main";
			}
			return "deleteUser_form";
		}
	}
}
